package com.cll.pmis.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.cll.pmis.common.Constants;
import com.cll.pmis.entity.Menu;
import com.cll.pmis.mapper.MenuMapper;
import com.cll.pmis.service.IMenuService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenliangliang
 * @since 2018-06-18
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Override
    public MenuMapper getMapper() {
        return this.baseMapper;
    }


    @Override
    public List<Menu> getUserMenus(Integer userId) {
        List<Menu> menuList;
        if (userId == Constants.SUPER_ADMIN) {
            menuList = baseMapper.selectList(new EntityWrapper<Menu>().orderBy("order_num",true));
        } else {
            menuList = baseMapper.queryUserMenus(userId);
        }
        return handleMenuList(menuList);

    }


    private List<Menu> handleMenuList(List<Menu> menuList) {

        System.out.println(menuList);
        //先找出目录
        List<Menu> catalog = new ArrayList<>();
        Iterator<Menu> it = menuList.iterator();
        Menu menu;
        while (it.hasNext()) {
            menu = it.next();
            if (menu == null) {
                it.remove();
                continue;
            }
            if (menu.getType() == Constants.MENU_TYPE_CATALOG) {
                catalog.add(menu);
                it.remove();
            } else if (menu.getType() == Constants.MENU_TYPE_BUTTON) {
                it.remove();
            }
        }
        for (Menu c : catalog) {
            List<Menu> subMenu = new LinkedList<>();
            for (Menu m : menuList) {
                if (c.getId().intValue() == m.getPid().intValue()) {
                    subMenu.add(m);
                }
            }
            c.setSubMenu(subMenu);
        }

        return catalog;
    }
}
